package com.wolfking.converter.transform.base;


import com.google.common.collect.Sets;
import com.wolfking.converter.transform.FieldTransform;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BooleanFieldTransform implements FieldTransform<Boolean> {

    private final Set<Class<?>> classes = Sets.newHashSet(Boolean.class, boolean.class);

    private final Map<String, Boolean> map = new HashMap<String, Boolean>() {
        {
            put("true", true);
            put("false", false);
            put("0", false);
            put("1", true);
        }
    };

    @Override
    public boolean canTransform(Class<?> fieldType) {
        return classes.contains(fieldType);
    }

    @Override
    public Boolean transform(Object value) {
        for (Class<?> clazz : classes) {
            if (clazz.isAssignableFrom(value.getClass())) {
                return (Boolean) value;
            }
        }
        String s = value.toString().toLowerCase();
        if (StringUtils.isNotBlank(s)) {
            Boolean aBoolean = map.get(s);
            if (aBoolean == null) {
                try {
                    int i = Integer.parseInt(s);
                    return i > 0;
                } catch (Exception e) {
                    throw new IllegalStateException("boolean 转换异常 " + s);
                }
            } else {
                return aBoolean;
            }
        } else {
            throw new IllegalStateException("boolean 转换空");
        }
    }
}
